package com.youlin.untils;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Properties;

public class CaptchaUtil {

    private CaptchaUtil() {
        throw new IllegalStateException("Utility class");
    }

    public static boolean validateCaptcha (RedisTemplate<String, Object> redisTemplate, String code) {
        if (StringUtils.isBlank(code)) return false;
        String str = RedisUtil.getObject(redisTemplate, "captcha:" + code, String.class);
        return StringUtils.isNotBlank(str);
    }

    public static String getCaptchaBase64 (RedisTemplate<String, Object> redisTemplate) throws IOException {
        BufferedImage bufferedImage = getCaptcha(redisTemplate);
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); //io流
        ImageIO.write(bufferedImage, "png", baos); //写入流中
        byte[] bytes = baos.toByteArray(); //转换成字节
        byte[] encode = Base64.getEncoder().encode(bytes);
        String png_base64 = new String(encode, 0, encode.length, "UTF-8").trim();
        png_base64 = png_base64.replaceAll("\n", "")
                .replaceAll("\r", ""); //删除 \r\n
        return "data:image/png;base64," + png_base64;
    }

    public static BufferedImage getCaptcha (RedisTemplate<String, Object> redisTemplate) {
        Properties properties = new Properties();
        properties.put("kaptcha.border", "no");
        properties.put("kaptcha.textproducer.font.color", "black");
        properties.put("kaptcha.textproducer.char.length", "5");
        properties.put("kaptcha.textproducer.char.space", "5");
        properties.put("kaptcha.textproducer.font.names", "Arial,Courier,cmr10,宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        //生成文字验证码
        String code = defaultKaptcha.createText();
        RedisUtil.setObjectExpire(redisTemplate,"captcha:"+code,"1234567890");
        return defaultKaptcha.createImage(code);
    }

}
